<template>
  <div class="product-attribute-container">
    <div class="header-actions">
      <h2>商品规格属性管理</h2>
      <el-button type="primary" icon="el-icon-plus" @click="handleAddAttribute">添加属性</el-button>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchId"
        placeholder="输入属性ID搜索"
        prefix-icon="el-icon-search"
        style="width: 200px;"
        @keyup.enter.native="fetchAttributes"
      ></el-input>
      <el-button type="primary" @click="fetchAttributes" style="margin-left: 10px;">按ID查询</el-button>
      <el-button @click="resetSearch" style="margin-left: 10px;">重置</el-button>
    </div>

    <div class="table-container">
      <el-table
        :data="attributeList"
        border
        stripe
        v-loading="loading"
      >
        <el-table-column prop="attrId" label="属性ID"></el-table-column>
        <el-table-column prop="spuId" label="商品ID"></el-table-column>
        <el-table-column prop="name" label="属性名称" ></el-table-column>
        <el-table-column prop="values" label="属性值"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.attrId)" style="margin-left: 10px;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑属性对话框 -->
    <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" width="50%">
      <el-form :model="attributeForm" ref="attributeForm" :rules="formRules" label-width="120px">
        <el-form-item label="商品ID" prop="spuId">
          <el-input v-model.number="attributeForm.spuId" placeholder="请输入商品ID"></el-input>
        </el-form-item>
        <el-form-item label="属性名称" prop="name">
          <el-input v-model="attributeForm.name" placeholder="请输入属性名称"></el-input>
        </el-form-item>
        <el-form-item label="属性值" prop="values">
          <el-input v-model="attributeForm.values" placeholder="请输入属性值，多个值用逗号分隔"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAttributeList, addAttribute, updateAttribute, deleteAttribute, getAttributeById } from '@/api/productApi';

export default {
  name: 'ProductAttribute',
  data() {
    return {
      attributeList: [],
      loading: false,
      searchId: '',
      dialogVisible: false,
      dialogTitle: '添加属性',
      attributeForm: {
        attrId: null,
        spuId: null,
        name: '',
        values: ''
      },
      formRules: {
        spuId: [
          { required: true, message: '请输入商品规格ID', trigger: 'blur' },
          { type: 'number', message: '商品规格ID必须为数字', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' }
        ],
        values: [
          { required: true, message: '请输入属性值', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.fetchAttributes();
  },
  methods: {
    fetchAttributes() {
      this.loading = true;
      console.log('开始查询，searchId:', this.searchId);
      if (this.searchId) {
        // 将searchId转换为数字类型
        const id = Number(this.searchId);
        console.log('转换后的ID:', id);
        if (isNaN(id)) {
          this.$message.error('请输入有效的数字ID');
          this.loading = false;
          return;
        }
        // 使用productApi中的getAttributeById方法
        console.log('使用productApi查询，ID:', id);
        // 添加详细日志，检查请求URL
        console.log('即将调用getAttributeById，当前API定义:', getAttributeById);
        getAttributeById(id)
          .then(response => {
            console.log('查询结果:', response);
            if (response.data) {
              this.attributeList = [response.data];
              this.$message.success('查询成功');
            } else {
              this.attributeList = [];
              this.$message.warning('未找到该属性');
            }
            this.loading = false;
          })
          .catch(error => {
            console.error('查询失败:', error);
            console.error('请求URL:', error.config.url);
            console.error('请求方法:', error.config.method);
            console.error('请求参数:', error.config.params);
            this.$message.error('获取属性失败: ' + (error.response?.data?.msg || error.message));
            this.loading = false;
          });
      } else {
        // 获取全部
        getAttributeList().then(response => {
          this.attributeList = response.data || [];
          this.loading = false;
        }).catch(error => {
          this.$message.error('获取属性列表失败: ' + (error.response?.data?.msg || error.message));
          this.loading = false;
        });
      }
    },

    handleAddAttribute() {
      this.dialogTitle = '添加属性';
      this.attributeForm = { attrId: null, spuId: null, name: '', values: '' };
      this.dialogVisible = true;
    },

    handleEdit(row) {
      this.dialogTitle = '编辑属性';
      // 使用productApi中的getAttributeById方法
      console.log('编辑操作，属性ID:', row.attrId);
      console.log('即将调用getAttributeById，当前API定义:', getAttributeById);
      getAttributeById(row.attrId)
        .then(response => {
          this.attributeForm = response.data;
          this.dialogVisible = true;
        })
        .catch(error => {
          console.error('获取属性详情失败:', error);
          console.error('请求URL:', error.config.url);
          console.error('请求方法:', error.config.method);
          console.error('请求参数:', error.config.params);
          this.$message.error('获取属性详情失败: ' + (error.response?.data?.msg || error.message));
        });
    },

    submitForm() {
      this.$refs.attributeForm.validate(valid => {
        if (valid) {
          console.log('提交的属性:', this.attributeForm);
          this.loading = true;
          const method = this.attributeForm.attrId ? updateAttribute : addAttribute;
          method(this.attributeForm)
            .then((obj) => {
              console.log('提交结果:', obj);
              if(obj.code === 0){
                this.$message.success(obj.msg);
              }else{
                this.$message.error(obj.msg);
              }
              this.dialogVisible = false;
              this.fetchAttributes();
            })
            .catch(error => {
              this.$message.error((this.attributeForm.attrId ? '更新' : '添加') + '失败: ' + error.message);
              this.loading = false;
            });
        }
      });
    },

    handleDelete(id) {
      this.$confirm('确定要删除该属性吗?', '提示', { type: 'warning' })
        .then(() => {
          this.loading = true;
          deleteAttribute(id)
            .then(() => {
              this.$message.success('删除成功');
              this.fetchAttributes();
            })
            .catch(error => {
              this.$message.error('删除失败: ' + error.message);
              this.loading = false;
            });
        })
        .catch(() => {});
    },

    resetSearch() {
      this.searchId = '';
      this.fetchAttributes();
    }
  }
};
</script>

<style scoped>
.product-attribute-container {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  flex-direction: column;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  width: 100%;
  box-sizing: border-box;
}

.table-container {
  flex: 1;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

::v-deep .el-table__header-wrapper,
::v-deep .el-table__body-wrapper,
::v-deep .el-table__footer-wrapper {
  width: 100% !important;
  height: 100% !important;
  border-radius: 8px;
  overflow: hidden;
  background: white;
  table-layout: fixed;
}

::v-deep .el-table__header th {
  background: linear-gradient(90deg, #3b82f6 0%, #60a5fa 100%);
  color: white;
  font-weight: bold;
}

::v-deep .el-table__body tr:hover > td {
  background-color: #f0f7ff !important;
  transition: background-color 0.2s;
}

::v-deep .el-table__cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 8px 12px;
}

::v-deep .el-button--primary {
  background: linear-gradient(90deg, #2563eb 0%, #3b82f6 100%);
  border: none;
}

::v-deep .el-button--primary:hover {
  background: linear-gradient(90deg, #1d4ed8 0%, #2563eb 100%);
}

::v-deep .el-button--danger {
  background: linear-gradient(90deg, #ef4444 0%, #f87171 100%);
  border: none;
}

::v-deep .el-button--danger:hover {
  background: linear-gradient(90deg, #dc2626 0%, #ef4444 100%);
}

::v-deep .el-table__body-wrapper {
  overflow-y: auto;
  scrollbar-width: none;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  display: none;
}

::v-deep .el-dialog__header {
  background: linear-gradient(90deg, #3b82f6 0%, #60a5fa 100%);
  color: white;
  border-radius: 8px 8px 0 0;
}

::v-deep .el-dialog__title {
  color: white;
  font-weight: bold;
}

::v-deep .el-dialog__body {
  padding: 20px;
  background-color: white;
}

::v-deep .el-dialog__footer {
  background-color: #f5f5f5;
  border-radius: 0 0 8px 8px;
  padding: 15px 20px;
  border-top: 1px solid #eee;
}
</style>